package com.xxx.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.xxx.util.CommonUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * PDF相关 Controller
 */
@RestController
@Slf4j
public class PdfController {

	/**
     * 生成PDF文件，并下载到本地
     */
    @RequestMapping("/pdf")
    public void pdf(HttpServletResponse response){
    	log.info("enter method pdf().");
    	
    	try {
    		// PO#列
    		List<String> po=new ArrayList<String>();
    		add(po, "po", 100);
    		// Line#列
    		List<String> line=new ArrayList<String>();
    		add(line, "line", 100);
    		// Part#列
    		List<String> part=new ArrayList<String>();
    		add(part, "part", 100);
    		// Description#列
    		List<String> description=new ArrayList<String>();
    		add(description, "description", 100);
    		// Origin#列
    		List<String> origin=new ArrayList<String>();
    		add(origin, "origin", 100);
    		
    		// 创建Document
    		Document document=new Document();
    		
    		// 添加字体
    		// 默认的iText字体设置不支持中文字体，需要下载远东字体包iTextAsian.jar，否则不能往PDF文档中输出中文字体。
    		BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

    		Font titleFont=new Font(bfChinese,20, Font.BOLD); // 标题部分字体大小
    		Font headerFont=new Font(bfChinese,8, Font.BOLD); // header部分字体大小
    		Font headerContentFont=new Font(bfChinese, 8, Font.NORMAL); // header内容部分字体大小
    		Font bodyFont=new Font(bfChinese, 8, Font.NORMAL); // body部分字体大小
    		
    		// 创建PdfWriter实例，并在指定文件夹下生成pdf文档
    		PdfWriter.getInstance(document, new FileOutputStream(new File("D:\\进货单.pdf")));
    		// 生成PDF，并下载到本地
//    		response.setContentType("application/pdf");
//    		OutputStream os = response.getOutputStream();
//    		PdfWriter.getInstance(document, os);
    		
    		// 打开文档
    		document.open();
    		
    		// 标题
    		document.add(new Paragraph("\n"+printBlank(55)+"进货单", titleFont));
    		// 作者
    		document.addAuthor("guwq");
    		// 主题
    		document.addSubject("This example explains how to add metadata.");
    		document.addKeywords("iText, Hello mingri");
    		document.addCreator("My program using iText");
    		//向文档中添加内容
    		document.add(new Paragraph("\n---------------------------------------------------------------------------------------------------------------------------------"));
    		document.add(new Paragraph("\n\n\n\n\n"));
    		document.add(new Paragraph("First page of the document.", bodyFont));
    		document.add(new Paragraph("First page of the document."));
    		document.add(new Paragraph("First page of the document."));
    		document.add(new Paragraph("First page of the document."));
    		document.add(new Paragraph("Some more text on the first page with different color and font type.", bodyFont));
    		document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"));
    		
    		// 计算分页参数
    		int recordPerPage=50; // 分页大小
    		int fullPageRequired=po.size()/recordPerPage; // 正常分页数量
    		int remainPage=po.size()%recordPerPage>1?1:0; // 剩余分页数量
    		int totalPage=fullPageRequired+remainPage; // 总页数
    		
    		// 添加分页信息
			String pageNo=CommonUtil.leftPad("页码: 1 / "+(totalPage+1), 615);
			Paragraph pageInfo=new Paragraph(pageNo, headerFont);
			pageInfo.setAlignment(Element.ALIGN_CENTER);
			document.add(pageInfo);
    		
    		for(int j=1;j<=totalPage;j++){
    			document.newPage(); // 新建一个page
    			
    			// 添加图片
    			Image jpeg=Image.getInstance("D:\\title.jpg"); // 需要提前准备好图片素材
    			jpeg.setAlignment(Image.ALIGN_CENTER);
    			jpeg.scaleAbsolute(418.5f, 30f);
    			document.add(jpeg);
    			
    			// 创建一个2列的table Header部分
    			String compAdd="河源市高新技术开发区兴业大道中66号";
				String company="丰达音响（河源）有限公司";
				String vendor="V006";
				String vendorName="中山市卢氏五金有限公司";
				String ccn="FHH";
				String mas_loc="FHH";
				String delivery_note="20130718001";
				String receive_date="20130718";
				String dept="H11";
				String asn="0123456789";
    			if(j==1) {
    				PdfPTable tHeader=new PdfPTable(4);
    				float[] widthsHeader={1f, 3f, 1f, 3f};
    				tHeader.setWidths(widthsHeader); // 设置相对宽度
    				tHeader.setTotalWidth(100f);
    				tHeader.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    				
    				PdfPCell c1Header=new PdfPCell(new Paragraph("地址：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(compAdd, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("供应商：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(vendor, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("公司：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(company, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("供应商工厂：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(vendorName, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header = new PdfPCell(new Paragraph("CCN：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header = new PdfPCell(new Paragraph(ccn, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("Master Loc：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(mas_loc, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header = new PdfPCell(new Paragraph("送货编号：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header = new PdfPCell(new Paragraph(delivery_note, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("送货日期：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(receive_date, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("Dept：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(dept, headerContentFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph("ASN：", headerFont));
    				tHeader.addCell(c1Header);
    				c1Header=new PdfPCell(new Paragraph(asn, headerContentFont));
    				tHeader.addCell(c1Header);
    				document.add(tHeader);
    			}
    			
    			// 创建一个5列的数据记录table部分
    			PdfPTable t=new PdfPTable(5);
    			float[] widths={1.5f, 1.5f, 1.5f, 1.5f, 1.5f};
    			t.setWidths(widths);
    			t.setTotalWidth(100);
    			t.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    			PdfPCell c1 = new PdfPCell(new Paragraph("PO#", headerFont));
    			t.addCell(c1);
    			c1 = new PdfPCell(new Paragraph("Line#", headerFont));
    			t.addCell(c1);
    			c1 = new PdfPCell(new Paragraph("Part#", headerFont));
    			t.addCell(c1);
    			c1 = new PdfPCell(new Paragraph("Description#", headerFont));
    			t.addCell(c1);
    			c1 = new PdfPCell(new Paragraph("Origin#", headerFont));
    			t.addCell(c1);
    			
    			//calculate the real records within a page ,to calculate the last record number of every page
    			int maxRecordInPage= j+1 ==totalPage ? (remainPage==0?recordPerPage:(po.size()%recordPerPage)):recordPerPage;
    			
    			for(int i=(j-1)*recordPerPage;i<(((j-1)*recordPerPage)+maxRecordInPage);i++){
    				PdfPCell c2=new PdfPCell(new Paragraph(po.get(i), bodyFont));
    				t.addCell(c2);
    				c2=new PdfPCell(new Paragraph(line.get(i), bodyFont));
    				t.addCell(c2);
    				c2=new PdfPCell(new Paragraph(part.get(i), bodyFont));
    				t.addCell(c2);
    				c2=new PdfPCell(new Paragraph(description.get(i), bodyFont));
    				t.addCell(c2);
    				c2=new PdfPCell(new Paragraph(origin.get(i), bodyFont));
    				t.addCell(c2);
    			}
    			document.add(t);
    			
    			if(j==totalPage){
    				Paragraph foot11 = new Paragraph("文件只作  Foster 收货用"+printBlank(150)+"__________________________", headerFont);
    				document.add(foot11);
    				Paragraph foot12 = new Paragraph("Printed from Foster supplier portal"+printBlank(124)+company+printBlank(40)+"版本: 1.0", headerFont);
    				document.add(foot12);
    			}
    			
    			// 添加分页信息
    			pageNo=CommonUtil.leftPad("页码: "+(j+1)+" / "+(totalPage+1), 615);
    			pageInfo=new Paragraph(pageNo, headerFont);
    			pageInfo.setAlignment(Element.ALIGN_CENTER);
    			document.add(pageInfo);
    		}
    		document.close();
//    		os.flush();
//    		os.close();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    // 模拟往表格里填充内容
    private static void add(List<String> list, String suffix, int num){
        for(int i=1;i<=num;i++){
            list.add(suffix + i);
        }
    }
     
    // 打印空白单元格
    private static String printBlank(int tmp){
    	String space="";
    	for(int m=0;m<tmp;m++){
    		space=space+" ";
    	}
    	return space;
    }
    
    /**
     * 给pdf文件设置水印
     * @param bos输出文件的位置
     * @param pdfFileName
     *            原PDF文件路径
     * @param footerWaterMark
     *            页脚水印
     * @throws DocumentException
     * @throws IOException
     */
    private static void setWatermark(BufferedOutputStream bos, String pdfFilePath, String footerWaterMark)
            throws DocumentException, IOException {
        PdfReader reader = new PdfReader(pdfFilePath);
        PdfStamper stamper = new PdfStamper(reader, bos);
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        PdfContentByte content;
        int total = reader.getNumberOfPages() + 1;
        // 循环处理每一页
        for (int i=1; i<total; i++) {
            content = stamper.getOverContent(i);// 在内容上方加水印
            // content = stamper.getUnderContent(i);//在内容下方加水印
            gs.setFillOpacity(0.2f);
            // content.setGState(gs);
            content.beginText();
            content.setColorFill(BaseColor.LIGHT_GRAY);
            content.setFontAndSize(font, 40);
            content.setTextMatrix(70, 200);
            content.showTextAligned(Element.ALIGN_CENTER, "公司内部文件，请注意保密！", 300, 350, 55);
            // 可以添加图片水印
            /*
            Image image = Image.getInstance("D:/title.jpg");
			img.setAlignment(Image.LEFT | Image.TEXTWRAP);
			img.setBorder(Image.BOX); img.setBorderWidth(10);
			img.setBorderColor(BaseColor.WHITE); img.scaleToFit(100072);//大小
			img.setRotationDegrees(-30);//旋转 
            image.setAbsolutePosition(200, 206); // set the first background image of the absolute
            image.scaleToFit(200, 200);
            content.addImage(image);
             */
            content.setColorFill(BaseColor.BLACK);
            content.setFontAndSize(font, 8);
            content.showTextAligned(Element.ALIGN_CENTER, footerWaterMark, 300, 10, 0);
            content.endText();
        }
        stamper.close();
    }
    
    /**
     * main测试
     * @param args
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws DocumentException, IOException {
        // 要输出的pdf文件
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/进货单1.pdf")));
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        // 将pdf文件先加水印然后输出
        setWatermark(bos, "D:/进货单.pdf", "下载时间："+format.format(cal.getTime())+"  下载使用人：测试user");
    }
}
